﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using DTO;
using BUS;

namespace MacroApp
{
    public partial class FrmAccountSettings : Form
    {
        public FrmAccountSettings()
        {
            InitializeComponent();
        }
        #region Declare
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
        private const string m_RunAs = "MyMailRe";
        public delegate void SEND();
        public SEND sender;
        #endregion
        private void FrmAccountSettings_Load(object sender, EventArgs e)
        {
            if (rkApp.GetValue(m_RunAs) == null)
            {
                // The value doesn't exist, the application is not set to run at startup
                chkRun.Checked = false;
            }
            else
            {
                // The value exists, the application is set to run at startup
                chkRun.Checked = true;
            }
            LoadInfo();
            LoadMailInfo();
        }
        private void chkRun_Click(object sender, EventArgs e)
        {
            if (chkRun.Checked)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue(m_RunAs, Application.ExecutablePath.ToString());
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue(m_RunAs, false);
            }
            MessageBox.Show("Check Run As StartUp Successful!", "Mail Receive");
        }
        private void btncancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
               
            if (!Functions.IsValidEmail(loginTextBox.Text))
            {
                MessageBox.Show("Email Error!", "Mail Receive");
                return;
            }
            if(!Functions.isInt(portTextBox.Text.Trim()))
            {
                MessageBox.Show("Port must be a number!", "Mail Receive");
                return;
            }
            if (!Functions.isInt(txtRepettion.Text.Trim()))
            {
                MessageBox.Show("Repetition time must be a number!", "Mail Receive");
                return;
            }
            if (!Functions.isInt(txtTimeout.Text.Trim()))
            {
                MessageBox.Show("Timeout must be a number!", "Mail Receive");
                return;
            }
            if (txtDataFoder.Text.Length == 0)
            {
                MessageBox.Show("Data Folder need to enter!", "Mail Receive");
                return;
            }
            this.SaveSetting();
            this.sender();
        }
        #region Private Method        
        private void SaveSetting()
        {
            string m_mailAddress;
            try
            {
                MailInfoDTO mail = new MailInfoDTO();
                mail.UserId = Program.UserId;
                mail.MailAddress = loginTextBox.Text.Trim();
                mail.PassWord = Functions.Encrypt(passwordTextBox.Text.Trim(), true);
                mail.MailServer = popServerTextBox.Text.Trim();
                mail.Port = portTextBox.Text.Trim();
                mail.TimeOut = txtTimeout.Text.Trim();

                if (useSslCheckBox.Checked)
                {
                    mail.SSl = true;
                }
                else
                {
                    mail.SSl = false;
                }
            
                mail.FolderIncome = txtDataFoder.Text.Trim();
                mail.FolderOutcome = txtOutCome.Text.Trim();
                mail.FolderBackup = txtBackUp.Text.Trim();
                mail.PassWordExcel = txtPassWordExcel.Text.Trim();
                mail.RepettionTime = (txtRepettion.Text.Trim());
                m_mailAddress = string.Format(@"{0}\{1}\{2}\{3}", txtDataFoder.Text.Trim(),txtuser.Text, "Income", loginTextBox.Text.Trim());
                if (!Directory.Exists(m_mailAddress))
                {
                    Directory.CreateDirectory(m_mailAddress);
                }
                if (MailInfoBUS.updateMailInfo(mail) == false)
                {
                    MessageBox.Show("loi");
                }
                string path = string.Format(@"{0}", txtBackUp.Text.Trim()) + @"\MailInfoDefault.txt";
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                using (FileStream fs = File.Create(path))
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes(txtMailInfo.Text);
                    fs.Write(info, 0, info.Length);
                }

                if (txtpass.Text.Trim().Length != 0)
                {
                    UserDTO user = new UserDTO();
                    user.Username = txtuser.Text;
                    user.Id = Program.UserId;
                    user.PassWord = txtpass.Text;
                    user.RuleUser = Program.rule;
                    user.StatusUser = true;
                    if (UserBUS.updateUser(user) != true)
                    {
                        MessageBox.Show("Error!!");
                        return;
                    }
                }
                MessageBox.Show("Succesfull!!!");
            }
            catch
            {
                MessageBox.Show("Error!!");
                return;
            }
        }
        private void LoadMailInfo()
        {
            string[] lines;
            string file = txtBackUp.Text + @"\" + "MailInfoDefault.txt"; // Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), @"MailInfoDefault.txt");
            if (File.Exists(file))
            {
                lines = File.ReadAllLines(file);
                if (lines.Length > 1)
                {
                    txtMailInfo.Clear();
                    txtMailInfo.Lines = lines;
                }
            }
            
        }
        private void LoadInfo()
        {
            // This is only for faster debugging purposes
            // We will try to load in default values for the hostname, port, ssl, username and password from a file     
            var dt = MailInfoBUS.getMailInfoById(Program.UserId);
            if (dt != null || dt.Rows.Count > 0)
            {
                loginTextBox.Text = dt.Rows[0][2].ToString(); // Username
                passwordTextBox.Text = Functions.Decrypt(dt.Rows[0][3].ToString(), true); // Password
                popServerTextBox.Text = dt.Rows[0][4].ToString();  // Hostname
                portTextBox.Text = dt.Rows[0][5].ToString(); // Port
                txtTimeout.Text = dt.Rows[0][6].ToString();
                useSslCheckBox.Checked = bool.Parse(dt.Rows[0][7].ToString() ?? "true"); // Whether to use SSL or not                    
                txtDataFoder.Text = dt.Rows[0][8].ToString(); // Folder Data
                txtOutCome.Text = dt.Rows[0][9].ToString(); //Out come
                txtBackUp.Text = dt.Rows[0][10].ToString(); //Backup
                txtPassWordExcel.Text = dt.Rows[0][12].ToString(); // Pass for excel
                txtRepettion.Text = dt.Rows[0][11].ToString();
                txtuser.Text = Program.username;
                
            }
            else
            {
                MessageBox.Show("Load Mail Config error!");
            }
        }
        #endregion
        #region textbox Events
        private void txtDataFoder_Click(object sender, EventArgs e)
        {
            string curPath = Directory.GetCurrentDirectory();
            fBDDataFolder.SelectedPath = "";
            DialogResult result = fBDDataFolder.ShowDialog();            
            if (result == DialogResult.OK)
            {
                txtDataFoder.Text = fBDDataFolder.SelectedPath;                
            }
            Directory.SetCurrentDirectory(curPath);
        }
        private void txtOutCome_Click(object sender, EventArgs e)
        {
            string curPath = Directory.GetCurrentDirectory();
            fBDDataFolder.SelectedPath = "";
            DialogResult result = fBDDataFolder.ShowDialog();        
            if (result == DialogResult.OK)
            {
                txtOutCome.Text = fBDDataFolder.SelectedPath;
            }
            Directory.SetCurrentDirectory(curPath);
        }
        private void txtBackUp_Click(object sender, EventArgs e)
        {
            string curPath = Directory.GetCurrentDirectory();
            fBDDataFolder.SelectedPath = "";
            DialogResult result = fBDDataFolder.ShowDialog();        
            if (result == DialogResult.OK)
            {
                txtBackUp.Text = fBDDataFolder.SelectedPath;
            }
            Directory.SetCurrentDirectory(curPath);
        }
        #endregion

       

    }
}
